var $,
    layer,
    form,
    upload,
    table;

layui.use(['jquery', 'layer', 'table', 'form', 'upload'], function () {
    $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        upload = layui.upload,
        table = layui.table;

    //是否启用
    form.on('switch(enabled)', function (data) {
        var name = data.value;
        var id = name.substring(0, name.indexOf('-'));
        name = name.substring(name.indexOf('-') + 1, name.lastIndexOf('-'));
        if (data.elem.checked){
            layer.open({
                type: 0,
                content: '您确定要启用' + name + '吗？',
                area: ['300px', '190px'],
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    layer.msg('启用成功', {icon: 6});
                    updateStatus(id, 1)
                },
                btn2:function (index, layero) {
                    layer.msg('启用取消', {icon: 5});
                    $('input[value='+data.value+']').siblings('.layui-unselect').removeClass('layui-form-onswitch');
                    data.elem.checked = false;
                }
            });
        }else {
            layer.open({
                type: 0,
                content: '您确定要停用' + name + '吗？',
                area: ['300px', '190px'],
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    layer.msg('停用成功', {icon: 5});
                    updateStatus(id, 2)
                },
                btn2:function (index, layero) {
                    layer.msg('停用取消', {icon: 6});
                    $('input[value='+data.value+']').siblings('.layui-unselect').addClass('layui-form-onswitch');
                    data.elem.checked = true;
                }
            });
        }
    });

    //账号状态
    form.on('switch(status)', function (data) {
        var name = data.value;
        var id = name.substring(0, name.indexOf('-'));
        name = name.substring(name.indexOf('-') + 1, name.lastIndexOf('-'));
        if (data.elem.checked){
            layer.open({
                type: 0,
                content: '您确定要解冻' + name + '吗？',
                area: ['300px', '190px'],
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    layer.msg('解冻成功', {icon: 6});
                    updateStatus(id, '',1)
                },
                btn2:function (index, layero) {
                    layer.msg('解冻取消', {icon: 5});
                    data.elem.checked = false;
                    form.render();
                }
            });
        }else {
            layer.open({
                type: 0,
                content: '您确定要冻结' + name + '吗？',
                area: ['300px', '190px'],
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    layer.msg('冻结成功', {icon: 5});
                    updateStatus(id, '', 3)
                },
                btn2:function (index, layero) {
                    layer.msg('冻结取消', {icon: 6});
                    data.elem.checked = true;
                    form.render();
                }
            });
        }
    });



    function updateStatus(id, enabled, status){
        $.ajax({
            url: '/User/updateUser',
            type: 'post',
            data: {
                'userId': id,
                'enabled': enabled,
                'status': status,
            },
            dataType: 'json',
        });
    };


    //导入用户
    var uploadInst = upload.render({
        elem: '#import'
        ,url: '/User/importUser'
        ,field:'file'
        ,exts: 'xls|xlsx'
        , done: function (res) {
            console.log(res.data)
            if (res.data){
                layer.msg('添加成功');
            }else {
                layer.msg('添加失败');
            }
        }
        , error: function () {
            // 演示失败状态，并实现重传
           layer.msg('上传失败');
        }
    });
});

//展示树
getDeptZtree();
function getDeptZtree() {

    //zTree的参数设置
    var zTreeObj
    //zTree的数据属性
    var setting = {
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "id",  //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId",  //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                name: "deptName",  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        callback: {
            onClick: zTreeOnClick,//鼠标点击到节点时回调
        },
    };
    function zTreeOnClick(event, treeId, treeNode) {
        getUseData(treeNode.id);
    };

    $.ajax({
        url: '/Dept/getDeptZtree',
        type: 'post',
        // async: false,
        dataType: 'json',
        success: function (item) {
            zTreeObj = $.fn.zTree.init($('#treeDemo'), setting, item.data);
            zTreeObj.expandAll(true);    //true 节点全部展开、false节点收缩
        }
    });
};

//查询用户信息
getUseData();
function getUseData(deptId, account, trueName, deptName, registerDate, email, phone, idCard, status, sex, enabled){
    if (deptId == null || deptId <= 0){
        deptId = deptName > 0 ? deptName : null;
    }
    $.ajax({
        url: '/User/getAllUser',
        type: 'post',
        dataType: 'json',
        data: {
            'deptId': deptId,
            'account': account,
            'trueName': trueName,
            'registerDate': registerDate,
            'email': email,
            'phone': phone,
            'idCard': idCard,
            'status': status,
            'sex': sex,
            'enabled': enabled,
        },
        success: function (item) {
            getUserTable(item.data);
        }
    });
};

//展示用户表
function getUserTable(data) {
    table.render({
        elem: '#demo',
        data: data,
        toolbar: true,
        cols: [[
            {type: 'checkbox'},
            {title:'序号', align:'center', templet:function (data) {
                    return data.LAY_INDEX;
                }},
            {field:'trueName',title:'用户姓名', align:'center'},
            {field:'acatarUrl',title:'用户头像',align:'center'},
            {field:'sex',title:'性别',align:'center'},
            {field:'account',title:'用户账号',align:'center'},
            {field:'deptName',title:'所属部门',align:'center'},
            {field:'enabled',title:'是否启用',align:'center', templet: function (data) {
                    if (data.enabled == 1){
                        return '<input type="checkbox" name="switch" value="'+data.userId+'-'+data.deptName+'-enabled'+'" lay-filter="enabled" lay-text="启用 | 停用" lay-skin="switch" checked>'
                    } else{
                        return '<input type="checkbox" name="switch" value="'+data.userId+'-'+data.deptName+'-enabled'+'" lay-filter="enabled" lay-text="启用 | 停用" lay-skin="switch">'
                    }

                }},
            {field:'status',title:'账号状态',align:'center', templet: function (data) {
                    if (data.status == 1){
                        return '<input type="checkbox" name="switch" value="'+data.userId+'-'+data.deptName+'-status'+'" lay-filter="status" lay-text="使用中 | 未使用" lay-skin="switch" checked>'
                    } else {
                        return '<input type="checkbox" name="switch" value="'+data.userId+'-'+data.deptName+'-status'+'" lay-filter="status" lay-text="使用中 | 未使用" lay-skin="switch">'
                    }

                }},
            {field:'registerDate',title:'注册时间',align:'center'},
            {title:'操作',align:'center', templet:function(data){
                    return "<a href='JavaScript:getUser(\"" + data.userId +  "\");' class='operation'>查看</a>" + '&nbsp;&nbsp;'
                        +"<a class='operation' href='javascript:updateAuthority(\"" + data.userId + "\");'>权限</a>" + '<br/>' +
                        "<a href='JavaScript:updateUser(\"" + data.userId +  "\");' class='operation'>编辑</a>" + '&nbsp;&nbsp;'
                        +"<a class='operation' href='javascript:closureUser(\"" + data.userId + "\", \"" + data.productName + "\");'>封停</a>" ;
                }},
        ]]
    });
};

//搜索
function search () {
    var data = form.val('searchForm');
    if (data.deptName != null && data.deptName != ''){
        $.ajax({
            url: '/Dept/getNameById',
            type: 'post',
            data: {'deptName': data.deptName},
            dataType: 'json',
            async: false,
            success: function (item) {
                data.deptName = item.data;
            }
        })
    }
    getUseData('', data.account, data.trueName, data.deptName, data.registerDate)
};

//高级检索
function accurate(){
    layer.open({
        type:2,
        title: '高级检索',
        content:"/authority/authority-precisesearch.html",
        area:['490px','500px'],
    })
};

//查看用户
function getUser(id) {
    layer.open({
        type: 2,
        offset: 't',
        resize: false,
        title: '查看用户信息',
        area: ['1380px', '820px'],
        content: '/authority/layer-backstage-selectUser.html?tx=' + encodeURI(id),
    });
};

//权限设置
function updateAuthority(id) {
    layer.open({
        type: 2,
        offset: 'auto',
        resize: false,
        title: '权限设置',
        area: ['840px', '540px'],
        content: '/authority/layer-backstage-updateAuthority.html?tx=' + encodeURI(id),
    });
};

//修改用户信息
function updateUser(id) {
    layer.open({
        type: 2,
        offset: 't',
        resize: false,
        title: '修改用户信息',
        area: ['1380px', '820px'],
        content: '/authority/layer-backstage-updateUser.html?tx=' + encodeURI(id),
        btn: ['编辑', '取消'],
        yes: function (index, layero) {
            var iframe = layero.find('iframe').contents();
            var account = iframe.find('input[name=account]').val();
            var trueName = iframe.find('input[name=trueName]').val();
            var phone = iframe.find('input[name=phone]').val();
            var idCard = iframe.find('input[name=idCard]').val();
            var birthDate = iframe.find('input[name=birthDate]').val();
            var deptName = iframe.find('input[name=deptName]').val();
            var registerDate = iframe.find('input[name=registerDate]').val();
            var registerIp = iframe.find('input[name=registerIp]').val();
            var email = iframe.find('input[name=email]').val();
            var freestyle = iframe.find('textarea[name=freestyle]').val();

            $.ajax({
                url: '/User/updateUser',
                type: 'post',
                dataType: 'json',
                data: {
                    'userId': id,
                    'account': account,
                    'trueName': trueName,
                    'phone': phone,
                    'idCard': idCard,
                    'birthDate': birthDate,
                    'deptName': deptName,
                    'registerDate': registerDate,
                    'registerIp': registerIp,
                    'email': email,
                    'freestyle': freestyle,
                },
                success: function (item) {
                    if (item.data){
                        layer.msg('修改成功')
                        layer.close(index);
                    }
                }
            });
        }
    });
};

//封停账户
function closureUser(id) {
    layer.open({
        type: 2,
        offset: 'auto',
        resize: false,
        title: '封停后台用户',
        area: ['690px', '500px'],
        content: '/authority/layer-backstage-closureUser.html?tx=' + encodeURI(id),
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            var form = layero.find('iframe').contents();
            var days = form.find('select[name=days]').val();
            var reason = form.find('textarea[name=reason]').val();
            var date = new Date();
            var startDate = new Date(date.getTime());
            var endDate = new Date(startDate.getTime() + (days * 24 * 60 * 60 * 1000));
            $.ajax({
                url: '/User/updateUser',
                type: 'post',
                dataType: 'json',
                data: {
                    'userId': id,
                    'status': 4,
                },
                success: function (item) {
                    if (item.data){
                        addClosure(id, reason, days, startDate, endDate, index);
                    }
                }
            });
        }
    });
};

//添加封停信息
function addClosure(id, reason, days, startDate, endDate, index){
    $.ajax({
        url: '/Closure/addClosure',
        type: 'post',
        dataType: 'json',
        data: {
            'userId': id,
            'type': 3,
            'reason': reason,
            'startDate': startDate,
            'endDate': endDate,
            'days': days,
        },
        success: function (item) {
            if (item.data){
                layer.close(index);
                layer.msg('封停成功');
            }
        }
    });
};

//添加用户
function addUser() {
    location.href='authority-addUser.html';
}


//刷新
function refresh () {
    location.reload();
};